<template>
  <div class="stories-page" v-loading="loading">
    <page-banner title="旅行故事" subtitle="发现最美川西,分享精彩瞬间" />

    <!-- 分类筛选区 -->
    <div class="filter-section">
      <div class="container">
        <div class="category-tabs">
          <el-radio-group v-model="selectedCategory" @change="handleCategoryChange">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button v-for="category in categories" 
              :key="category.value" 
              :label="category.value"
            >
              {{ category.label }}
            </el-radio-button>
          </el-radio-group>
        </div>
      </div>
    </div>

    <!-- 故事列表 -->
    <div class="stories-section">
      <div class="container">
        <el-row :gutter="30">
          <el-col :lg="8" :md="12" :sm="24" v-for="story in stories" :key="story.id">
            <div class="story-card hover-effect" @click="viewStory(story.id)">
              <div class="card-cover">
                <el-image :src="getImageUrl(story.coverImage)" fit="cover">
                  <template #placeholder>
                    <div class="image-placeholder">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
                <div class="category-tag" :class="getCategoryClass(story.category)">
                  {{ story.category }}
                </div>
              </div>
              <div class="card-content">
                <h3 class="story-title">{{ story.title }}</h3>
                <p class="story-excerpt">{{ story.excerpt }}</p>
                <div class="story-meta">
                  <div class="author-info">
                    <el-avatar :size="32" :src="story.authorAvatar" />
                    <span class="author-name">{{ story.authorName }}</span>
                  </div>
                  <div class="stats">
                    <span class="stat-item">
                      <el-icon><View /></el-icon>
                      {{ formatNumber(story.views) }}
                    </span>
                    <span class="stat-item">
                      <el-icon><Star /></el-icon>
                      {{ formatNumber(story.likes) }}
                    </span>
                    <span class="publish-date">{{ story.publishDate }}</span>
                  </div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>

        <!-- 空状态 -->
        <el-empty v-if="stories.length === 0" 
          description="暂无相关故事"
          :image-size="200"
        />

        <!-- 分页器 -->
        <div class="pagination-wrapper" v-if="total > 0">
          <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            background
            layout="prev, pager, next"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import { getStories, getStoriesByCategory, getAllCategories } from "@/api/story"; // 修改导入
import { formatNumber, getImageUrl } from "@/utils/format";
import { ElMessage, ElLoading } from "element-plus";
import { Picture, View, Star } from '@element-plus/icons-vue';
import PageBanner from "@/components/PageBanner.vue";

const router = useRouter();
const stories = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(9);
const selectedCategory = ref("");
const loading = ref(false);
const categories = ref([
  { label: '摄影游记', value: 'photo' },
  { label: '美食探店', value: 'food' },
  { label: '行程攻略', value: 'guide' },
  { label: '人文风情', value: 'culture' }
]);

// 获取所有分类
const fetchCategories = async () => {
  try {
    const categoryList = await getAllCategories();
    if (categoryList && categoryList.length > 0) {
      categories.value = categoryList.map(cat => ({
        label: cat,
        value: cat
      }));
    }
  } catch (error) {
    console.error("获取分类失败:", error);
  }
};

// 获取故事列表
const fetchStories = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      limit: pageSize.value
    };
    
    let response;
    
    // 根据是否选择分类调用不同的接口
    if (selectedCategory.value) {
      response = await getStoriesByCategory(selectedCategory.value, params);
    } else {
      response = await getStories(params);
    }
    
    if (response) {
      // 确保数据格式正确
      stories.value = response.list || [];
      total.value = response.total || 0;
      
      // 处理数据格式，确保与模板匹配
      stories.value = stories.value.map(story => ({
        id: story.id,
        title: story.title,
        excerpt: story.excerpt || story.summary || '',
        coverImage: story.coverImage || '',
        category: story.category || '旅行攻略',
        authorName: story.authorName || (story.author ? story.author.name : '旅行者'),
        authorAvatar: story.authorAvatar || (story.author ? story.author.avatar : ''),
        publishDate: story.publishDate || story.createTime || '',
        views: story.stats?.views || story.views || 0,
        likes: story.stats?.likes || story.likes || 0,
        comments: story.stats?.comments || story.comments || 0
      }));
    }
  } catch (error) {
    console.error("获取故事列表失败:", error);
    ElMessage.error("获取数据失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 分类切换
const handleCategoryChange = () => {
  currentPage.value = 1;
  fetchStories();
};

// 页码切换
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchStories();
  // 平滑滚动到顶部
  window.scrollTo({ top: 0, behavior: "smooth" });
};

// 查看故事详情
const viewStory = (id) => {
  router.push(`/story/${id}`);
};

// 获取分类样式
const getCategoryClass = (category) => {
  const classes = {
    'photo': 'photo',
    'food': 'food',
    'guide': 'guide',
    'culture': 'culture'
  };
  return classes[category] || 'default';
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

onMounted(async () => {
  // 使用 ElLoading 服务显示加载状态
  const loadingInstance = ElLoading.service({
    text: '加载中...',
    background: 'rgba(255, 255, 255, 0.7)'
  });
  
  try {
    // 先获取分类，再获取故事列表
    await fetchCategories();
    await fetchStories();
  } finally {
    loadingInstance.close();
  }
});

// 监听分类变化
watch(selectedCategory, () => {
  handleCategoryChange();
});
</script>

<style scoped>
.stories-page {
  background: var(--light-bg);
  min-height: 100vh;
}

.filter-section {
  background: white;
  padding: 20px 0;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: var(--header-height);
  z-index: 10;
}

.category-tabs {
  display: flex;
  justify-content: center;
}

.stories-section {
  padding: 40px 0;
}

.story-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  margin-bottom: 30px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.story-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0,0,0,0.1);
}

.card-cover {
  position: relative;
  height: 240px;
}

.card-cover .el-image {
  width: 100%;
  height: 100%;
}

.category-tag {
  position: absolute;
  top: 16px;
  right: 16px;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 0.9rem;
  color: white;
  backdrop-filter: blur(8px);
}

.category-tag.photo { background: rgba(19, 194, 194, 0.8); }
.category-tag.food { background: rgba(250, 84, 28, 0.8); }
.category-tag.guide { background: rgba(82, 196, 26, 0.8); }
.category-tag.culture { background: rgba(114, 46, 209, 0.8); }

.card-content {
  padding: 20px;
}

.story-title {
  font-size: 1.2rem;
  color: var(--text-color);
  margin: 0 0 12px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.story-excerpt {
  color: var(--text-color-secondary);
  font-size: 0.95rem;
  line-height: 1.6;
  margin: 0 0 20px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.story-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15px;
  border-top: 1px dashed var(--border-color);
}

.author-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.author-name {
  font-size: 0.95rem;
  color: var(--text-color);
}

.stats {
  display: flex;
  align-items: center;
  gap: 15px;
  color: var(--text-color-secondary);
  font-size: 0.9rem;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.publish-date {
  color: var(--text-color-secondary);
  font-size: 0.85rem;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  background: var(--light-bg);
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-color-secondary);
  font-size: 24px;
}

.pagination-wrapper {
  margin-top: 40px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .filter-section {
    position: static;
    padding: 15px;
  }

  .category-tabs {
    overflow-x: auto;
    padding: 0 15px;
  }

  .stories-section {
    padding: 20px 0;
  }

  .card-cover {
    height: 200px;
  }

  .story-title {
    font-size: 1.1rem;
  }

  .story-excerpt {
    -webkit-line-clamp: 2;
  }

  .story-meta {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }

  .stats {
    width: 100%;
    justify-content: space-between;
  }
}
</style>
